package com.xujie.sportsmeeting.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.dto.UserDTO;
import com.xujie.sportsmeeting.dto.UserQueryDTO;
import com.xujie.sportsmeeting.entity.SysUser;
import com.xujie.sportsmeeting.service.SysUserService;
import com.xujie.sportsmeeting.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 */
@Tag(name = "用户管理", description = "用户管理相关接口")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final SysUserService sysUserService;

    @Operation(summary = "获取用户列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<IPage<UserVO>> getUserList(UserQueryDTO queryDTO) {
        IPage<SysUser> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        IPage<SysUser> userPage = sysUserService.getUserPage(page, queryDTO);
        
        // 转换为VO
        IPage<UserVO> voPage = userPage.convert(user -> {
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(user, vo);
            // 获取用户角色
            vo.setRoles(sysUserService.findRolesByUserId(user.getId()));
            return vo;
        });
        
        return Result.success(voPage);
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<UserVO> getUserDetail(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        vo.setRoles(sysUserService.findRolesByUserId(id));
        vo.setPermissions(sysUserService.findPermissionsByUserId(id));
        
        return Result.success(vo);
    }

    @Operation(summary = "创建用户")
    @PostMapping
    @PreAuthorize("hasAuthority('system:user:add') or authentication.name == 'admin'")
    public Result<Void> createUser(@Valid @RequestBody UserDTO userDTO) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        
        boolean success = sysUserService.createUser(user);
        if (success) {
            return Result.success("用户创建成功");
        } else {
            return Result.error("用户创建失败");
        }
    }

    @Operation(summary = "更新用户信息")
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:edit') or authentication.name == 'admin'")
    public Result<Void> updateUser(@PathVariable Long id, @Valid @RequestBody UserDTO userDTO) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        user.setId(id);
        
        boolean success = sysUserService.updateUser(user);
        if (success) {
            return Result.success("用户更新成功");
        } else {
            return Result.error("用户更新失败");
        }
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:delete') or authentication.name == 'admin'")
    public Result<Void> deleteUser(@PathVariable Long id) {
        boolean success = sysUserService.removeById(id);
        if (success) {
            return Result.success("用户删除成功");
        } else {
            return Result.error("用户删除失败");
        }
    }

    @Operation(summary = "批量删除用户")
    @DeleteMapping("/batch")
    @PreAuthorize("hasAuthority('system:user:delete') or authentication.name == 'admin'")
    public Result<Void> batchDeleteUsers(@RequestBody List<Long> ids) {
        boolean success = sysUserService.removeByIds(ids);
        if (success) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    @Operation(summary = "重置用户密码")
    @PutMapping("/{id}/password")
    @PreAuthorize("hasAuthority('system:user:edit') or authentication.name == 'admin'")
    public Result<Void> resetPassword(@PathVariable Long id, @RequestBody ResetPasswordRequest request) {
        boolean success = sysUserService.resetPassword(id, request.getNewPassword());
        if (success) {
            return Result.success("密码重置成功");
        } else {
            return Result.error("密码重置失败");
        }
    }

    @Operation(summary = "启用/禁用用户")
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('system:user:edit') or authentication.name == 'admin'")
    public Result<Void> toggleUserStatus(@PathVariable Long id, @RequestBody StatusRequest request) {
        boolean success = sysUserService.updateUserStatus(id, request.getStatus());
        if (success) {
            return Result.success("用户状态更新成功");
        } else {
            return Result.error("用户状态更新失败");
        }
    }

    @Operation(summary = "获取角色列表")
    @GetMapping("/roles")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<List<RoleVO>> getRoleList() {
        List<RoleVO> roles = sysUserService.getAllRoles();
        return Result.success(roles);
    }

    @Operation(summary = "分配用户角色")
    @PutMapping("/{userId}/roles")
    @PreAuthorize("hasAuthority('system:user:edit') or authentication.name == 'admin'")
    public Result<Void> assignUserRoles(@PathVariable Long userId, @RequestBody AssignRolesRequest request) {
        boolean success = sysUserService.assignUserRoles(userId, request.getRoleIds());
        if (success) {
            return Result.success("角色分配成功");
        } else {
            return Result.error("角色分配失败");
        }
    }

    // 内部请求类
    public static class ResetPasswordRequest {
        private String newPassword;
        
        public String getNewPassword() {
            return newPassword;
        }
        
        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }

    public static class StatusRequest {
        private Integer status;
        
        public Integer getStatus() {
            return status;
        }
        
        public void setStatus(Integer status) {
            this.status = status;
        }
    }

    public static class AssignRolesRequest {
        private List<Long> roleIds;
        
        public List<Long> getRoleIds() {
            return roleIds;
        }
        
        public void setRoleIds(List<Long> roleIds) {
            this.roleIds = roleIds;
        }
    }

    public static class RoleVO {
        private Long id;
        private String roleName;
        private String roleCode;
        
        // getters and setters
        public Long getId() {
            return id;
        }
        
        public void setId(Long id) {
            this.id = id;
        }
        
        public String getRoleName() {
            return roleName;
        }
        
        public void setRoleName(String roleName) {
            this.roleName = roleName;
        }
        
        public String getRoleCode() {
            return roleCode;
        }
        
        public void setRoleCode(String roleCode) {
            this.roleCode = roleCode;
        }
    }
}
